package io.xxx.eve.task;

import io.xxx.eve.receiver.Room;
import io.xxx.eve.receiver.RoomRepository;
import io.xxx.eve.robot.Robot;
import io.xxx.eve.robot.Talker;
import io.xxx.eve.robot.TalkerFactory;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.NonNull;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;

@Slf4j
@Component
public class SingleTaskJob extends QuartzJobBean {

    @Autowired
    private TaskRepository taskRepository;

    @Autowired
    private TaskMessageRepository taskMessageRepository;

    @Autowired
    private RoomRepository roomRepository;

    @Autowired
    private TalkerFactory talkerFactory;

    @Override
    protected void executeInternal(@NonNull JobExecutionContext context) throws JobExecutionException {
        JobDataMap jobDataMap = context.getMergedJobDataMap();
        long taskId = jobDataMap.getLong("taskId");
        Optional<Task> taskOptional = taskRepository.findById(taskId);
        if (taskOptional.isPresent()) {
            Task task = taskOptional.get();
            try {
                List<TaskMessage> messages = taskMessageRepository.findByTask(task);
                if (messages.isEmpty()) {
                    return;
                }
                List<Room> rooms = roomRepository.findTop1000();
                for (Room room : rooms) {
                    Robot robot = room.getSeller().getRobots().get(0);
                    Talker talker = talkerFactory.getTalker(robot);
                    talker.say(task, room, messages);
                }
            } catch (Exception e) {
                task.setRetryTimes(task.getRetryTimes() + 1);
                taskRepository.save(task);
                JobExecutionException jee = new JobExecutionException(e);
                if (task.getRetryTimes() <= 3) {
                    jee.setRefireImmediately(true);
                }
                throw jee;
            }
        }
    }
}
